package com.s63.ssm.service;

import com.s63.ssm.dao.MenuMapper;
import com.s63.ssm.entity.Router;
import com.s63.ssm.entity.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<SysMenu> getAll() {
        return menuMapper.getAll();
    }

    @Override
    public List<Router> buildMenu(List<SysMenu> menuList) {
        return buildTree(menuList.stream()
                .filter(sysMenu -> !sysMenu.getMenuType().equals("F"))
                .collect(Collectors.toList()), 0L);
    }

    private List<Router> buildTree(List<SysMenu> menuList, Long parentId) {
        List<Router> list = new ArrayList<>();
        for (SysMenu sysMenu : menuList) {
            if (sysMenu.getParentId() != null && sysMenu.getParentId().equals(parentId)) {
                Router router = new Router();
                router.setId(sysMenu.getMenuId());
                router.setName(sysMenu.getMenuName());
                router.setPath(sysMenu.getPath());
                router.setComponent(sysMenu.getComponent());
                router.setChildren(buildTree(menuList, sysMenu.getMenuId()));
                list.add(router);
            }
        }
        return list;
    }
}
